<?php

// +----------------------------------------------------------------------
// | 系统配置
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace app\common\event;

use think\Exception;
use think\facade\Cache;
use think\facade\Config;
use app\common\model\SystemConfig as SystemConfigModel;
use yicmf\builder\Edit;

class SystemConfig extends Base
{
    /**
     * 加载配置
     */
    public static function parse()
    {
        if (!Cache::has('system_config_cache1')) {
            $groups = SystemConfigModel::where('status', 1)->distinct(true)->cache(true)->field('group')->column('group');
            foreach ($groups as $group) {
                $lists = SystemConfigModel::where('status', 1)
                    ->where('group', $group)
                    ->cache('config_cache_' . $group . '_db', 600)
                    ->select();
                $configs = [];
                foreach ($lists as $index => $list) {
                    if ($list['parse'] == 'array') {
                        if (is_array(json_decode($list['value'],true)))
                        {
                            $configs[$list['name']] = json_decode($list['value'],true);
                        }else{
                            $configs[$list['name']] = explode(',', $list['value']);
                        }
                    } else {
                        $configs[$list['name']] = $list['value'];
                    }
                }
                self::_saveFile($group, $configs);
                Config::set($configs, $group);
            }
            Cache::set('system_config_cache', 1, 30);
        }
    }

    protected static function _saveFile($group, $configs)
    {
        $file = root_path() . 'config' . DIRECTORY_SEPARATOR . $group . '.php';
        if (is_file($file)) {
            $configs = array_merge(config($group), $configs);
        }
        // 配置文件模版
        $config_tpl = file_get_contents(app()->getRootPath() . 'data' . DIRECTORY_SEPARATOR . 'tpl' . DIRECTORY_SEPARATOR . 'default.tpl');
        $value_tpl = '';
        if (is_array($configs)) {
            foreach ($configs as $name => $value) {
                if (is_array($value)) {
                    $temp = '[';
                    foreach ($value as $key2 => $value2) {
                        if (count($value) == ($key2 + 1)) {
                            $temp .= '\'' . $value2 . '\'';
                        } else {
                            $temp .= '\'' . $value2 . '\',';
                        }
                    }
                    $temp .= ']';
                    $value_tpl .= '\'' . $name . '\' => ' . $temp . ',
                ';
                } else {

                    $value_tpl .= '\'' . $name . '\' => \'' . $value . '\',
                ';
                }
            }
            $config_tpl = str_replace('{$value}', $value_tpl, $config_tpl);
            $config_tpl = str_replace('{$title}', '自动生成配置文件', $config_tpl);
            $config_tpl = str_replace('{$data_year}', time_format(time(), 'Y'), $config_tpl);
        }
        // 写入配置
        return file_put_contents($file, $config_tpl);
    }

    /**
     * 生成配置view
     * @param $items
     * @param $title
     * @param array $explain
     * @return string
     */
    public static function builderView($items, $title, array $explain = []): string
    {
        $builder = new Edit();
        $builder->title($title);

        $data = [];
        $groups = [];
        foreach ($items as $item) {
            $data[$item['group']][$item['name']] = config($item['group'].'.'.$item['name']);
//            $data[$item['group']][$item['name']] = $item['value'];
            $groups[$item['tab']][] = $item['group'] . '.' . $item['name'];
            if ($item['type'] == 'input') {
                $builder->keyTextInline($item['group'] . '.' . $item['name'], $item['title'], $item['tips']);
            } elseif ('switch' == $item['type']) {
                $builder->keyBool($item['group'] . '.' . $item['name'], $item['title'], $item['tips'], $item['value']);
            } elseif ('color' == $item['type']) {
                $builder->keyColor($item['group'] . '.' . $item['name'], $item['title'], $item['tips'], $item['value']);
            } elseif ('textarea' == $item['type']) {
                $builder->keyTextArea($item['group'] . '.' . $item['name'], $item['title'], $item['tips']);
            } elseif ('number' == $item['type']) {
                $builder->keyNumber($item['group'] . '.' . $item['name'], $item['title'], $item['tips']);
            } elseif ('image_model' == $item['type']) {
                $builder->keyImageModel($item['group'] . '.' . $item['name'], $item['title'], $item['tips']);
            } elseif ('image' == $item['type']) {
                $builder->keyImage($item['group'] . '.' . $item['name'], $item['title'], $item['tips']);
            } elseif ('select' == $item['type'] || 'radio' == $item['type']) {
                $options = explode("\r\n", trim($item['options']));
                $ops = [];
                foreach ($options as $index => $option) {
                    $op = explode(':', trim($option));
                    $ops[$op[0]] = $op[1];
                }
                if ('radio' == $item['type']) {
                    $builder->keyRadio($item['group'] . '.' . $item['name'], $item['title'], $ops, $item['tips']);
                } else {
                    $builder->keySelect($item['group'] . '.' . $item['name'], $item['title'], $ops, $item['tips']);
                }
            } elseif ('checkbox' == $item['type']) {
                $options = explode("\r\n", trim($item['options']));
                $ops = [];
                foreach ($options as $index => $option) {
                    $op = explode(':', trim($option));
                    $ops[$op[0]] = $op[1];
                }

//>keyCheckBox('types', '接收方式', [ 'email' => '邮件'],'',['email'])
                $builder->keyCheckBox($item['group'] . '.' . $item['name'], $item['title'], $ops, $item['tips']);

            } else {
                dump($item);
            }
        }
        foreach ($groups as $key => $item) {
            $builder->group($key, $item);
        }
        foreach ($explain as $item) {
            $builder->explain($item);
        }
        $builder->data($data)
            ->buttonSubmit();
        return $builder->fetch();
    }

    /**
     * 更新配置
     * @param $param
     * @param $user
     * @return array
     */
    public function updateValue($param, $user): array
    {
        try {
            $line = 0;
            foreach ($param as $group => $item) {

                if (is_array($item)) {
                    foreach ($item as $name => $value) {

                        $line++;
                        SystemConfigModel::where('status', 1)
                            ->where('group', $group)
                            ->where('name', $name)->update(['value' => is_array($value)?json_encode($value):$value]);
                    }
                }
            }
            if (0 == $line) {
                throw new Exception('配置未更新');
            }
            $data['code'] = 0;
            $data['data'] = $line;
            $data['message'] = '成功更新' . $line . '条配置';
        } catch (Exception $e) {
            // 回滚事务
            $data['code'] = 1;
            $data['message'] = $e->getMessage();
        }
        return $data;
    }
}
